package dao

import (
	"goWeb/bookStore/model"
	"goWeb/bookStore/utils"
	"net/http"
)

//添加session
func AddSession(sess *model.Session) (err error) {
	sqlstr := "insert into session values(?,?,?)"
	instmt, err := utils.Db.Prepare(sqlstr)
	if err != nil {
		return err
	}
	_, err = instmt.Exec(sess.SessionId, sess.Username, sess.Userid)
	if err != nil {
		return err
	}
	return nil
}

//删除session
func DelSession(SessionId string) (err error) {
	sqlstr := "delete from session where sessionid=?"
	_, err = utils.Db.Exec(sqlstr, SessionId)
	return err
}

//获取session
func GetSession(SessionId string) (sess *model.Session, err error) {
	sqlstr := "select sessionid,username,userid from session where sessionid=?"
	instmt, err := utils.Db.Prepare(sqlstr)
	if err != nil {
		return nil, err
	}
	row := instmt.QueryRow(SessionId)
	sess = &model.Session{}
	row.Scan(&sess.SessionId, &sess.Username, &sess.Userid)
	return sess, nil
}

func IsLogin(r *http.Request) (flag bool, session *model.Session) {
	cookie, _ := r.Cookie("user")
	if cookie != nil {
		sess, _ := GetSession(cookie.Value)
		if sess.Userid > 0 {
			return true, sess
		}
	}
	return false, nil

}
